package com.shop.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

	private static  SessionFactory sessionFactory;
	public static Session getSession(){
		Session session = null;
		//读取hibernate.cfg.xml
		//Configuration configuration = new Configuration();
		ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().configure().build();
		//连接池
		sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
		//sessionFactory=configuration.buildSessionFactory(serviceRegistry);
		//sessionFactory = new Configuration().configure().buildSessionFactory();
		//相当于一个数据库连接 Connection
		session = sessionFactory.openSession();
		return session;
	}
	public static void main(String[] args) {
		System.out.println(getSession());
	}
	public static void closeSession(Session session){
		if(session != null){
			session.close();
		}
		if(sessionFactory!=null){
			sessionFactory.close();
		}
	}
}
